package com.cloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @BelongsProject: my
 * @BelongsPackage: com.cloud.lb
 * @Author: ji ge
 * @CreateTime: 2024-02-02  11:44
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class MyLoadBalanceImpl implements MyLoadBalance {

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement() {
        int current;
        String a = "current";
        int next = 0;
        do {
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!atomicInteger.compareAndSet(current, next));
        return next;

    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> instances) {
        int idx = getAndIncrement() % instances.size();
        return instances.get(idx);
    }
}
